package com.tanhua.server.server;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domian.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.FriendsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private VisitorsApi visitorsApi;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }


    public void updatehead(MultipartFile headPhoto,Long id) throws IOException {
        //将图片上传到阿里云oss
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        log.info("upload={}",upload);
        //调用百度云人脸判断是否有人脸
        boolean detect = aipFaceTemplate.detect(upload);
        //如果不包含人脸，做出异常
        if (!detect) {
            //throw new RuntimeException("审核未通过");
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //包含人脸，调用Api更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(upload);
            userInfoApi.updete(userInfo);
        }



    }

    public UserInfo findById(Long userID) {
        UserInfo byId = userInfoApi.findById(userID);
        return byId;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.updete(userInfo);
    }


    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     * 4 = 谁看过我 , 1 = 互相喜欢,2=喜欢，3=粉丝
     * @param type
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult friends(String type, Integer page, Integer pagesize,String nickname) {
        int types = Integer.parseInt(type);
        Long userId = UserHolder.getUserId();
        ArrayList<FriendsVo> vos = new ArrayList<>();
        switch (types){
            //互相喜欢的
            case 1:
                ArrayList<UserLike> userLikes = new ArrayList<>();
                //mongDB里面查询我喜欢的数量
                List <UserLike> loveCounts  =  userLikeApi.loveCount(userId);
                //mongDB里面查询喜欢我的的数量
                List <UserLike> fanCounts =  userLikeApi.fanCount(userId);
                Map<Long, UserLike> fanCountsMap = CollUtil.fieldValueMap(fanCounts, "userId");
                for (UserLike loveCount : loveCounts) {
                    UserLike userLike = fanCountsMap.get(loveCount.getLikeUserId());
                      if (userLike != null) {
                          userLikes.add(userLike);
                      }
                }
                //-----------------------------------------------------------------------------------------
                List<Long> userIds = CollUtil.getFieldValues(userLikes, "userId", Long.class);
                //查询userinfo表把数据封装到vo
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setNickname(nickname);
                Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, userInfo1);
                if (userInfoMap == null) {
                    return new PageResult();
                }
                //查询recommend_user表擦查询缘分值
                Map<Long, RecommendUser> recommendUserMap = recommendUserApi.queryFateValue(userId,userIds);
                for (UserLike userLike : userLikes) {
                    UserInfo userInfo = userInfoMap.get(userLike.getUserId());
                    RecommendUser recommendUser = recommendUserMap.get(userLike.getUserId());
                    if (userInfo != null){
                        FriendsVo init = FriendsVo.init(userInfo);
                        if (recommendUser==null) {
                            int integer = (int) (Math.random() * 100 - 30);
                            Integer num = Integer.valueOf(integer);
                            init.setMatchRate(num);
                        }else {
                            int i = recommendUser.getScore().intValue();
                            Integer s = Integer.valueOf(i);
                            Integer num = Integer.valueOf(s);
                            init.setMatchRate(num);
                        }
                        init.setAlreadyLove(true);
                        vos.add(init);
                    }
                }
                break;
            //我喜欢的
            case 2 :
                //查询userlike表，查询出我喜欢的
                List<UserLike> userLikes1 = userLikeApi.loveCount(userId);
                List<Long> userIds1 = CollUtil.getFieldValues(userLikes1, "likeUserId", Long.class);
                //查询userinfo表把数据封装到vo
                UserInfo userInfo11 = new UserInfo();
                userInfo11.setNickname(nickname);
                Map<Long, UserInfo> userInfoMap1 = userInfoApi.findByIds(userIds1, userInfo11);
                if (userInfoMap1 == null) {
                    return new PageResult();
                }
                //查询recommend_user表擦查询缘分值
                Map<Long, RecommendUser> recommendUserMap1 = recommendUserApi.queryFateValue(userId,userIds1);
                for (UserLike userLike : userLikes1) {
                    UserInfo userInfo = userInfoMap1.get(userLike.getLikeUserId());
                    RecommendUser recommendUser = recommendUserMap1.get(userLike.getUserId());
                    if (userInfo != null){
                        FriendsVo init = FriendsVo.init(userInfo);
                        if (recommendUser==null) {
                            int integer = (int) (Math.random() * 100 - 30);
                            Integer num = Integer.valueOf(integer);
                            init.setMatchRate(num);
                        }else {
                            int i = recommendUser.getScore().intValue();
                            Integer s = Integer.valueOf(i);
                            Integer num = Integer.valueOf(s);
                            init.setMatchRate(num);
                        }
                        init.setAlreadyLove(true);
                        vos.add(init);
                    }
                }
                break;
            //喜欢我的
            case 3 :
                //查询userlike表，查询出喜欢我的
                List<UserLike> userLikes2 = userLikeApi.fanCount(userId);
                List<Long> userIds2 = CollUtil.getFieldValues(userLikes2, "userId", Long.class);
                //查询userinfo表把数据封装到vo
                UserInfo userInfo12 = new UserInfo();
                userInfo12.setNickname(nickname);
                Map<Long, UserInfo> userInfoMap2 = userInfoApi.findByIds(userIds2, userInfo12);
                if (userInfoMap2 == null) {
                    return new PageResult();
                }
                //查询recommend_user表擦查询缘分值
                Map<Long, RecommendUser> recommendUserMap2 = recommendUserApi.queryFateValue(userId,userIds2);
                for (UserLike userLike : userLikes2) {
                    UserInfo userInfo = userInfoMap2.get(userLike.getUserId());
                    RecommendUser recommendUser = recommendUserMap2.get(userLike.getUserId());
                    if (userInfo != null){
                        FriendsVo init = FriendsVo.init(userInfo);
                        if (recommendUser==null) {
                            int integer = (int) (Math.random() * 100 - 30);
                            Integer num = Integer.valueOf(integer);
                            init.setMatchRate(num);
                        }else {
                            int i = recommendUser.getScore().intValue();
                            Integer s = Integer.valueOf(i);
                            Integer num = Integer.valueOf(s);
                            init.setMatchRate(num);
                        }
                        init.setAlreadyLove(true);
                        vos.add(init);
                    }
                }
                break;
            //谁看过我
            case 4 :
                //去visitors表查询看过我账户的ID
                List<Visitors> visitorsList = visitorsApi.queryVisitorsList(null,UserHolder.getUserId());
                if(CollUtil.isEmpty(visitorsList)) {
                    return new PageResult(page,pagesize,0,vos);
                }
                //根据ID找到用户详细userinfo
                UserInfo userInfo13 = new UserInfo();
                userInfo13.setNickname(nickname);
                List<Long> visitorUserIds = CollUtil.getFieldValues(visitorsList, "visitorUserId", Long.class);
                Map<Long, UserInfo> userInfoMap3 = userInfoApi.findByIds(visitorUserIds, userInfo13);
                if (userInfoMap3 == null) {
                    return new PageResult();
                }
                //查询recommend_user表擦查询缘分值
                Map<Long, RecommendUser> recommendUserMap3 = recommendUserApi.queryFateValue(userId,visitorUserIds);
                for (Visitors visitors : visitorsList) {
                    UserInfo userInfo = userInfoMap3.get(visitors.getVisitorUserId());
                    RecommendUser recommendUser = recommendUserMap3.get(visitors.getVisitorUserId());
                    if (userInfo != null){
                        FriendsVo init = FriendsVo.init(userInfo);
                        if (recommendUser==null) {
                            int integer = (int) (Math.random() * 100 - 30);
                            Integer num = Integer.valueOf(integer);
                            init.setMatchRate(num);
                        }else {
                            int i = recommendUser.getScore().intValue();
                            Integer s = Integer.valueOf(i);
                            Integer num = Integer.valueOf(s);
                            init.setMatchRate(num);
                        }
                        init.setAlreadyLove(true);
                        vos.add(init);
                    }
                }
                break;
            default :
                throw new BusinessException(ErrorResult.error());

        }
        return new PageResult(page,pagesize,0,vos);
    }
}
